/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.wsr.impl;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import javax.xml.namespace.QName;

import cgl.narada.wsinfra.schemas.wsr.NonSequenceReplyType;
import cgl.narada.wsinfra.schemas.wsr.ReplyRangeType;
import cgl.narada.wsinfra.schemas.wsr.ResponseDocument;
import cgl.narada.wsinfra.schemas.wsr.SequenceRepliesType;
import cgl.narada.wsinfra.wsr.WsrAckOperations;


/** A utility class to deal with processing acknowledgements.

    @author Sima Patel
    $Date: 2005/05/04 18:05:34 $
    $Revision: 1.7 $
*/


public class WsrAckOperationsImpl implements WsrAckOperations {
  
    private static final WsrAckOperations instance = new WsrAckOperationsImpl();
    private WsrFaultsImpl wsrFaultsImpl;
 
    private String moduleName = "WsrAckOperations: ";

    private WsrAckOperationsImpl() {
        wsrFaultsImpl = WsrFaultsImpl.getInstance();
    }

    public static WsrAckOperations getInstance() {
        return instance;
    }
    /** Retrieves groupIds of single message and already acknowledged 
    from response document(Retrieves Acknowledgements for Non Sequence Reply from 
    response document */
    public Vector getNonSequenceReplyAcknowledgement
                                            (ResponseDocument responseDocument){       
        Vector nonSequenceReplyAcknowledgementVector = null;
        NonSequenceReplyType nonSequenceReplyType[]=
                      responseDocument.getResponse().getNonSequenceReplyArray();
        if(nonSequenceReplyType.length !=0){
            nonSequenceReplyAcknowledgementVector = new Vector();
            for(int i=0;i< nonSequenceReplyType.length;i++){
                if(nonSequenceReplyType[i].isSetFault()){
                    continue;
                }else{
                    nonSequenceReplyAcknowledgementVector.addElement
                                         (nonSequenceReplyType[i].getGroupId());
                }
            }
        }
        return nonSequenceReplyAcknowledgementVector;
    }
    /** Retrieves Vector of groupIds of single message and have Message 
    Processing Failure Fault from response document. (Retrieves Message 
    Processing Failure Faults for Non Sequence Reply from 
    response document. 
    These are the groupIds for which retransmission is scheduled*/
    public Vector getNonSequenceReplyMessageProcessingFailureFault
                                            (ResponseDocument responseDocument){
        Vector nonSequenceReplyRetransmissionVector = null;
        NonSequenceReplyType nonSequenceReplyType[]=
                      responseDocument.getResponse().getNonSequenceReplyArray();
        if(nonSequenceReplyType.length !=0){
            nonSequenceReplyRetransmissionVector= new Vector();
            for(int count = 0; count < nonSequenceReplyType.length; count++){
                if(nonSequenceReplyType[count].isSetFault()){
                    if(isMessageProcessingFailureFault(
                                       nonSequenceReplyType[count].getFault())){
                        nonSequenceReplyRetransmissionVector.add(
                                      nonSequenceReplyType[count].getGroupId());
                    }
                }
            }
        }
        return nonSequenceReplyRetransmissionVector;
    }
    /** Retrieves Hashtable (groupId and fault pair) for groups with 
    single message and have faults other than Message Processing Failure Fault
    from response document. The hashtable contains those groupIds which are
    not for retrasmission. In this case send fault to application 
    along with details of failure*/
    public Hashtable getNonSequenceReplyFault(
                                             ResponseDocument responseDocument){
        Hashtable nonSequenceReplyFaultTable = new Hashtable();
        NonSequenceReplyType nonSequenceReplyType[]=
                      responseDocument.getResponse().getNonSequenceReplyArray();
        if(nonSequenceReplyType.length !=0){
            for(int count = 0; count < nonSequenceReplyType.length; count++){
                if(nonSequenceReplyType[count].isSetFault()){
                    if(!isMessageProcessingFailureFault
                                      (nonSequenceReplyType[count].getFault())){
                        nonSequenceReplyFaultTable.put(
                         nonSequenceReplyType[count].getGroupId(),
                         nonSequenceReplyType[count].getFault()); 
                    }
                }
            }
        }
        return nonSequenceReplyFaultTable;
    }
    /** Retrieves Hashtable (groupId and associated acknowledged 
    sequence numbers in vector) for groups with multiple messages from 
    response document. Retrieves Sequence Replies acknowledgements*/
    public Hashtable getSequenceRepliesAcknowledgement(
                                             ResponseDocument responseDocument){
    	  Hashtable sequenceReplyAcknowledgementTable = new Hashtable();
        SequenceRepliesType sequenceRepliesType[] = 
                       responseDocument.getResponse().getSequenceRepliesArray();
        if(sequenceRepliesType != null && sequenceRepliesType.length != 0){
           for(int count =0; count < sequenceRepliesType.length; count++){
                String groupId = sequenceRepliesType[count].getGroupId();
                ReplyRangeType[] replyRange =  
                                sequenceRepliesType[count].getReplyRangeArray();
                Vector acknowledgements = new Vector();
                for(int i=0; i<replyRange.length; i++){
                    if(!replyRange[i].isSetFault()){
                        long from = replyRange[i].getFrom().longValue();
                        long to = replyRange[i].getTo().longValue();
                        while(from <= to){
                            acknowledgements.addElement(new Long(from));
                            from++;
                        }
                        
                    }
                }
                sequenceReplyAcknowledgementTable.put(
                        groupId, acknowledgements);  
                
            }
        }
        return sequenceReplyAcknowledgementTable;
    }
    /** Retrieves Hashtable(groupId and vector of sequence numbers) for groups 
    with multiple messages and have Message Processing Failure Fault from 
    response document (Retrieves Message Processing Failure Faults for Sequence 
    Reply from response document */
    public Hashtable getSequenceReplyMessageProcessingFailureFault(
                                             ResponseDocument responseDocument){
       
        Hashtable sequenceReplyRetransmissionTable = new Hashtable();
        SequenceRepliesType sequenceRepliesType[] = 
                      responseDocument.getResponse().getSequenceRepliesArray();
        if(sequenceRepliesType.length != 0){
            for(int count =0; count < sequenceRepliesType.length; count++){
                String groupId = sequenceRepliesType[count].getGroupId();
                ReplyRangeType[] replyRange =  
                       sequenceRepliesType[count].getReplyRangeArray();
                Vector messageProcessingFaults = new Vector();
                for(int i=0; i<replyRange.length; i++){
                    if(replyRange[i].isSetFault()){
                        QName faultName = replyRange[i].getFault();
                        if(isMessageProcessingFailureFault(faultName)){
                            long from = replyRange[i].getFrom().longValue();
                            long to = replyRange[i].getTo().longValue();
                            while(from <= to){
                                messageProcessingFaults.addElement(
                                                               new Long(from));
                                from++;
                            }
                            
                        }
                    }
                }
                sequenceReplyRetransmissionTable.put(groupId,
                        messageProcessingFaults); 
                 
            }
        }
        return sequenceReplyRetransmissionTable;
    }
    /** Retrieves Hashtable (groupId and Hashtable(sequenceNumber and fault name)) 
    for groups with multiple messages and have faults other than 
    Message Processing Failure Fault from response document. 
    The hashtable contains those groupIds which are
    not for retrasmission. In this case send fault to application 
    along with details of failure*/
    public Hashtable getSequenceReplyFault(ResponseDocument responseDocument){
    	
        Hashtable sequenceReplyFaultTable = new Hashtable();
        SequenceRepliesType sequenceRepliesType[] = 
                       responseDocument.getResponse().getSequenceRepliesArray();
        if(sequenceRepliesType.length != 0){
            for(int count =0; count < sequenceRepliesType.length; count++){
                String groupId = sequenceRepliesType[count].getGroupId();
                
                ReplyRangeType[] replyRange =  
                                sequenceRepliesType[count].getReplyRangeArray();
                Hashtable faults = new Hashtable();
                for(int i=0; i<replyRange.length; i++){
                    if(replyRange[i].isSetFault()){
                        QName faultName = replyRange[i].getFault();
                        
                        if(!isMessageProcessingFailureFault(faultName)){
                        	
                            long from = replyRange[i].getFrom().longValue();
                            long to = replyRange[i].getTo().longValue();
                            while(from <= to){
                                faults.put(new Long(from),faultName);
                                from++;
                            }
                            
                        }
                    }
                }
                sequenceReplyFaultTable.put(groupId, faults); 
            }

        }
        return sequenceReplyFaultTable;
    }
   
    /** Retrieve all groupIds from Response Document for which we 
    receive acknowledgements and faults*/
    public String[] getGroupIds(ResponseDocument responseDocument){
        Vector groupIds = new Vector();
        NonSequenceReplyType nonSequenceReplyType[]=
                      responseDocument.getResponse().getNonSequenceReplyArray();
        if(nonSequenceReplyType.length !=0){
            for(int i=0;i<nonSequenceReplyType.length;i++){
                groupIds.addElement(nonSequenceReplyType[i].getGroupId());
            }
        }
        SequenceRepliesType sequenceRepliesType[] = 
                       responseDocument.getResponse().getSequenceRepliesArray();
        if(sequenceRepliesType.length != 0){
            for(int index=0;index<sequenceRepliesType.length;index++){
                groupIds.addElement(sequenceRepliesType[index].getGroupId());
            }
        }
        String[] groupId = new String[groupIds.size()];
        for(int count=0;count<groupIds.size();count++){
            groupId[count]=groupIds.elementAt(count).toString();
        }
        return groupId;     
       
    }
    /** create ranges from array of sequence Numbers */
    public Hashtable createRanges(long[] seqNums){
        if (seqNums == null || seqNums.length == 0) {
            return null;
        }
        Hashtable ranges = new Hashtable();
        /** Deal with the case where there is only one Sequence number
        to process*/
        if (seqNums.length == 1) {
            ranges.put(new Long(seqNums[0]), new Long(seqNums[0]));
            return ranges;
        }
        /** First sort the acks, since the algo will work on the sorted array */
        Arrays.sort(seqNums);

        long lowerRange, upperRange;
        for (int i=0; i < seqNums.length -1; ) {
            lowerRange = seqNums[i];

            /** If successive elements are seperated by a value of 1 they can be
            part of a range */
            while (seqNums[i] + 1 == seqNums[i+1]) {
                i++;
                if (i >= seqNums.length -1 ) {
                    break;
                }
            }
            upperRange = seqNums[i];
            if (lowerRange == upperRange) {
            /** This implies that this value should be a standalone value */
                ranges.put(new Long(lowerRange),new Long(upperRange));
               
                i++;

                if (i == seqNums.length -1) {
                    ranges.put(new Long(seqNums[i]),new Long(seqNums[i]));
                }
                if (i >= seqNums.length -1 ) {
                    break;
                }
            } else {
                ranges.put(new Long(lowerRange),new Long(upperRange));
                
                i++;
                if (i >= seqNums.length -1 ) {
                    break;
                }
            }

        }/* end for */
        return ranges; 
    }/*end method */
 

    /** create ranges from Hashtable of sequence Numbers and Faults*/
    public Hashtable createRanges(Hashtable seqNumsAndFaults){
        if (seqNumsAndFaults == null || seqNumsAndFaults.size() == 0) {
            return null;
        }

        /** Deal with the case where there is only one Sequence number 
         and fault to process*/
        if(seqNumsAndFaults.size() == 1) {
            Hashtable faultAndRanges = new Hashtable();
            Enumeration keys = seqNumsAndFaults.keys();
            Hashtable ranges = new Hashtable();
            String fault=null;
            while(keys.hasMoreElements()){
                Long seqNum = ((Long)(keys.nextElement()));
                fault = seqNumsAndFaults.get(seqNum).toString();
                ranges.put(seqNum, seqNum);
            }
            faultAndRanges.put(ranges,fault);
            return faultAndRanges;
        }
        long lowerRange, upperRange;
        Enumeration keys = seqNumsAndFaults.keys();
        if(keys != null){

            Long seqNumLong1 = ((Long)(keys.nextElement()));
            long seqNum1 = seqNumLong1.longValue();
            String fault1 = seqNumsAndFaults.get(seqNumLong1).toString();
            upperRange = seqNum1;
            Long seqNumLong2;
            long seqNum2;
            String fault2 ;
            Hashtable faultAndRange = new Hashtable();
            /** If successive elements are seperated by a value of 1 
            and they have same fault in question then they 
            can be part of a range */
            while(keys.hasMoreElements()){
                seqNumLong2 = ((Long)(keys.nextElement()));
                seqNum2 = seqNumLong2.longValue();
                fault2 = seqNumsAndFaults.get(seqNumLong2).toString();
                if((seqNum1-1 == seqNum2)&&(fault1.equalsIgnoreCase(fault2))){
                    seqNum1 = seqNum2;
                    fault1 = fault2;
                    continue;
                }else{
                    lowerRange = seqNum1;
                    Hashtable range1 = new Hashtable();
                    range1.put(new Long(lowerRange),new Long(upperRange));
                    faultAndRange.put(range1, fault1);
                    seqNum1 = seqNum2;
                    fault1 = fault2;
                    upperRange = seqNum2;
                    continue;
                }
            }
            lowerRange = seqNum1;
            Hashtable range = new Hashtable();
            range.put(new Long(lowerRange),new Long(upperRange));
            faultAndRange.put(range,fault1);
            return faultAndRange;
        }else{
            return null;
        }
    }/*end method */
    /** Checks the fault is Message Processing failure */
    public boolean isMessageProcessingFailureFault(QName fault){
        if(fault.equals(wsrFaultsImpl.getMessageProcessingFailure())){
            return true;
        }else{
            return false;
        }
    }
}
